﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using BEGDC.CC.BL.Common.Query;
using BEGDC.CC.Entity;
using BEGDC.CC.BL.Common;
using BEGDC.CC.BL.Workflow;
using BEGDC.Utility.Castle;
using BEGDC.CC.BL.Email;
using ASBCC.Business;

namespace BEGDC.CC.Web.View
{
	/// <summary>
	/// Summary description for CustomerAttendee.
	/// </summary>
	public class CustomerAttendee : System.Web.UI.Page
	{
		protected System.Web.UI.WebControls.Button btnSearch;
		protected System.Web.UI.WebControls.DataGrid dgTaskList;
		protected System.Web.UI.WebControls.Label lblRecordCount;
		protected System.Web.UI.WebControls.Label lblCurrentPageIndex;
		protected System.Web.UI.WebControls.Label lblPageCount;
		protected System.Web.UI.WebControls.ImageButton btnPageFirst;
		protected System.Web.UI.WebControls.ImageButton btnPagePrev;
		protected System.Web.UI.WebControls.ImageButton btnPageNext;
		protected System.Web.UI.WebControls.ImageButton btnPageLast;
		protected System.Web.UI.WebControls.TextBox txtPage;
		protected System.Web.UI.WebControls.TextBox txtCustomerName;
		protected System.Web.UI.WebControls.Button btnExport;
		protected System.Web.UI.WebControls.DropDownList ddlDepartment;
		protected System.Web.UI.WebControls.TextBox txtApplicant;
		protected System.Web.UI.WebControls.TextBox txtEndDate;
		protected System.Web.UI.WebControls.TextBox txtStartDate;
		protected System.Web.UI.HtmlControls.HtmlImage StartDateImg;
		protected System.Web.UI.HtmlControls.HtmlImage EndlDateImg;
		protected System.Web.UI.WebControls.ImageButton btnGotoPage;

		private string _Sorting
		{
			get
			{
				if( ViewState["Sorting"] == null ) return string.Empty;

				return ViewState["Sorting"].ToString(); 
			}
			set{ ViewState["Sorting"]=value; }
		}
	
		private void Page_Load(object sender, System.EventArgs e)
		{
			// Put user code to initialize the page here
			if( !IsPostBack )
			{
				InitializeDropDownList();
				BindData(1);
			}
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    
			this.btnExport.Click += new System.EventHandler(this.btnExport_Click);
			this.btnSearch.Click += new System.EventHandler(this.btnSearch_Click);
			this.dgTaskList.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.dgTaskList_ItemCommandNew);
			this.dgTaskList.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.dgTaskList_ItemDataBound);
			this.btnPageFirst.Click += new System.Web.UI.ImageClickEventHandler(this.btnPageFirst_Click);
			this.btnPagePrev.Click += new System.Web.UI.ImageClickEventHandler(this.btnPagePrev_Click);
			this.btnPageNext.Click += new System.Web.UI.ImageClickEventHandler(this.btnPageNext_Click);
			this.btnPageLast.Click += new System.Web.UI.ImageClickEventHandler(this.btnPageLast_Click);
			this.btnGotoPage.Click += new System.Web.UI.ImageClickEventHandler(this.btnGotoPage_Click);
			this.dgTaskList.SortCommand += new System.Web.UI.WebControls.DataGridSortCommandEventHandler(this.dgTaskList_SortCommand);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		private void BindData(int pageIndex)
		{
			IQuery queryService = AppContainer.Instance[ServiceConst.QueryService] as IQuery;
			DataTable table = queryService.GetCustomerNeedConfirm();
			string filter = string.Empty;
			CCPrincipal empl = (CCPrincipal)HttpContext.Current.User;

            this.txtCustomerName.Text = PageSafeHelper.SafeText(this.txtCustomerName.Text);
            this.txtApplicant.Text = PageSafeHelper.SafeText(this.txtApplicant.Text);
            txtStartDate.Text = PageSafeHelper.SafeText(txtStartDate.Text);
            txtEndDate.Text = PageSafeHelper.SafeText(txtEndDate.Text);
			if (this._IsSearch)
			{
				if (this.txtCustomerName.Text.Trim() != string.Empty)
				{
					filter = " NameEN like '%" + this.txtCustomerName.Text.Trim() + "%'";
				}
				if (this.ddlDepartment.SelectedValue != "-1")
				{
					if (filter != string.Empty)
						filter += " and ";
					filter += " departmentid = " + ddlDepartment.SelectedValue;
				}
				if (this.txtApplicant.Text.Trim() != string.Empty)
				{
					if (filter != string.Empty)
						filter += " and ";
					filter += " RequesterNameEN like '%" + this.txtApplicant.Text + "%'";
				}

				if (txtStartDate.Text != string.Empty)
				{
					if (filter != string.Empty)
						filter += " and ";
					filter += " RequestDate >= '" + this.txtStartDate.Text + "'";
				}

				if (this.txtEndDate.Text != string.Empty)
				{
					if (filter != string.Empty)
						filter += " and ";
					filter += " RequestDate <= '" + this.txtEndDate.Text + "'";
				}
			}

			if (empl.Roles.IndexOf("'"+BEGDC.CC.BL.Workflow.UserRole.BusinessAdmin+"'") > 0)
			{
				if (filter != string.Empty)
					filter += " and ";
				filter += " ApplicationType in('EV','CV','CR','CO')";
			}
			else if(empl.Roles.IndexOf("'"+BEGDC.CC.BL.Workflow.UserRole.OCOBusinessAdmin+"'") > 0)
			{
				if (filter != string.Empty)
					filter += " and ";
				filter += " ApplicationType in('OCR','OCV')";
			}

			table.DefaultView.RowFilter = filter;
		
			if (this._Sorting != string.Empty)
			{
				table.DefaultView.Sort = this._Sorting;
			}

			this.dgTaskList.DataSource = table.DefaultView;;
			this.dgTaskList.DataBind();

			int count = table.DefaultView.Count;

			SetPageCount(count, pageIndex);

		}

		private void InitializeDropDownList()
		{
			//Department
			BEGDC.CC.BL.UserManagement.IUser userService = AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.UserService] as BEGDC.CC.BL.UserManagement.IUser;
			this.ddlDepartment.DataSource = userService.GetBusinessGroupList();
			this.ddlDepartment.DataValueField = "ID";
			this.ddlDepartment.DataTextField = "DepartmentCode";
			this.ddlDepartment.DataBind();
			this.ddlDepartment.Items.Insert(0,new System.Web.UI.WebControls.ListItem("All","-1"));
			this.ddlDepartment.SelectedIndex = 0;
		}

		private void SetPageCount(int count, int pageIndex)
		{
			if( count > 0 )
			{
				_RowCount = count;
				_PageCount = count / this.dgTaskList.PageSize;
				if( count % this.dgTaskList.PageSize > 0) _PageCount ++;

				_CurrentPageIndex = pageIndex;	
				SetPageNavi( pageIndex );
			}	
			else
			{
				_RowCount = count;
				_PageCount = count;
				_CurrentPageIndex = 0;
				SetPageNavi( 0 );
			}
		}

		private void SetPageNavi( int newPage )
		{
			if( newPage <= 1 )
			{
				this.btnPageFirst.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path+"/images/pg_first_inact.gif";
				this.btnPagePrev.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path+"/images/pg_pre_inact.gif";
				this.btnPageFirst.Attributes["disabled"] = "true";
				this.btnPagePrev.Attributes["disabled"] = "true";
			}
			else
			{
				this.btnPageFirst.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path+"/images/pg_first.gif";
				this.btnPagePrev.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path+"/images/pg_pre.gif";
				this.btnPageFirst.Attributes.Remove("disabled");
				this.btnPagePrev.Attributes.Remove("disabled");
			}

			if( newPage >= _PageCount )
			{
				this.btnPageNext.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path+"/images/pg_next_inact.gif";
				this.btnPageLast.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path+"/images/pg_last_inact.gif";
				this.btnPageNext.Attributes["disabled"] = "true";
				this.btnPageLast.Attributes["disabled"] = "true";
			}
			else
			{
				this.btnPageNext.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path+"/images/pg_next.gif";
				this.btnPageLast.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path+"/images/pg_last.gif";
				this.btnPageNext.Attributes.Remove("disabled");
				this.btnPageLast.Attributes.Remove("disabled");
			}

			this.lblCurrentPageIndex.Text = newPage.ToString();
			this.lblPageCount.Text = _PageCount.ToString();
			this.lblRecordCount.Text = _RowCount.ToString();

		}




		private int _PageCount
		{
			get
			{
				if( ViewState["PageCount"] != null ) return (int) ViewState["PageCount"];
				else
					return 0;
			}
			set
			{
				ViewState["PageCount"] = value;
			}
		}
		private int _CurrentPageIndex
		{
			get
			{
				if( ViewState["CurrentPageIndex"] != null ) return (int) ViewState["CurrentPageIndex"];
				else
					return 0;
			}
			set
			{
				ViewState["CurrentPageIndex"] = value;
			}
		}
		private int _RowCount
		{
			get
			{
				if( ViewState["RowCount"] != null ) return (int) ViewState["RowCount"];
				else
					return 0;
			}
			set
			{
				ViewState["RowCount"] = value;
			}
		}

		private void btnPageFirst_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			this.dgTaskList.CurrentPageIndex = 0;
			this.BindData(1);
		}

		private void btnPagePrev_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			if( _CurrentPageIndex == 1 ) return;
			this.dgTaskList.CurrentPageIndex = _CurrentPageIndex-2;
			this.BindData(_CurrentPageIndex - 1);
		}

		private void btnPageNext_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			if( _CurrentPageIndex == _PageCount ) return;	
			this.dgTaskList.CurrentPageIndex = _CurrentPageIndex;
			this.BindData( _CurrentPageIndex + 1 );
		}

		private void btnPageLast_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			this.dgTaskList.CurrentPageIndex = _PageCount-1;
			this.BindData( _PageCount );
		}

		private void btnGotoPage_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			if (this.txtPage.Text == string.Empty)	
			{
				this.txtPage.Text = "1";
			}
			int gotopage = 1;
			try
			{
				gotopage = Convert.ToInt32(this.txtPage.Text);
			}
			catch{}
			int currentpage = 0;

			if (gotopage >= _PageCount)	
			{
				gotopage = _PageCount;
				currentpage = gotopage - 1;
				if (currentpage < 0) currentpage = 0;
			}
			else if (gotopage <= 0)
			{
				gotopage = 1;
			}
			else
			{
				currentpage = gotopage -1;
			}

			this.dgTaskList.CurrentPageIndex = currentpage;

			this.BindData( gotopage );

			this.txtPage.Text = string.Empty;
		}

//		private void dgTaskList_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
//		{
//			if( e.CommandName == "Confirm" )
//			{
//				string attendeeId = e.Item.Cells[0].Text;
//				BEGDC.CC.BL.Common.IUtility utiService = AppContainer.Instance[ServiceConst.UtilityService] as BEGDC.CC.BL.Common.IUtility;
//				utiService.UpdateCustomerAttendee( Convert.ToInt32( attendeeId ) );
//
//				this.BindData( this._CurrentPageIndex );
//			}
//		}

		private void dgTaskList_ItemCommandNew(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
		{
			if( e.CommandName == "Confirm" )
			{
				string attendeeId = e.Item.Cells[0].Text;
				BEGDC.CC.BL.Common.IUtility utiService = AppContainer.Instance[ServiceConst.UtilityService] as BEGDC.CC.BL.Common.IUtility;
				utiService.UpdateCustomerAttendee( Convert.ToInt32( attendeeId ) );

				//Send mail
				CCPrincipal empl = (CCPrincipal)HttpContext.Current.User;
				if(empl.Roles.IndexOf("'"+BEGDC.CC.BL.Workflow.UserRole.OCOBusinessAdmin+"'") > 0)
				{
					int appid = Convert.ToInt32(e.Item.Cells[8].Text);
					IEmail email = AppContainer.Instance[ServiceConst.EmailService] as IEmail;
					email.Send(appid, EmailTemplate.CISReminder);
				}

				this.BindData( this._CurrentPageIndex );
			}
		}

		private void dgTaskList_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
		{
			if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
			{
				ImageButton btnDel = (ImageButton)e.Item.Cells[5].FindControl("ibtnConfirm");
				btnDel.Attributes.Add("onclick","return confirm('Are you sure to clear the not in CIS flag?')");
			}
		}

		/// <summary>
		/// 
		/// </summary>
		private bool _IsSearch
		{
			get
			{
				if( ViewState["_IsSearch"] == null ) return false;

				return Convert.ToBoolean( ViewState["_IsSearch"]); 
			}
			set{ ViewState["_IsSearch"]=value; }
		}

		private void btnSearch_Click(object sender, System.EventArgs e)
		{
			this.dgTaskList.CurrentPageIndex = 0;

			if (this.txtCustomerName.Text.Trim() == string.Empty && this.txtApplicant.Text.Trim() == string.Empty && this.ddlDepartment.SelectedValue == "-1" && this.txtStartDate.Text == string.Empty && this.txtEndDate.Text == string.Empty)
			{
				this._IsSearch = false;
				this.BindData(1);
				return;
			}
			this._IsSearch = true;

			this.BindData(1);
		}

		private void btnExport_Click(object sender, System.EventArgs e)
		{
			this.dgTaskList.AllowPaging = false;
			this.BindData(1);
			BEGDC.CC.Web.Control.ExportDataGridToExcel.Export(Page, this.dgTaskList, "Customer.xls");
		}

		public void dgTaskList_SortCommand(object source, DataGridSortCommandEventArgs e)
		{
			if (this._Sorting.IndexOf(e.SortExpression) > -1 && this._Sorting == e.SortExpression)
				this._Sorting = e.SortExpression + " desc";
			else
				this._Sorting = e.SortExpression;
			this.BindData(this._CurrentPageIndex);
			
		}
	}
}
